const http = require('http');
const fs = require('fs');
const url = require('url');
const globalConf = require('./config.js');
const loader = require('./loader.js');
// const web = require('')
// console.log(globalConf);
if(globalConf.static_file_type){
    var static_file_type_arr = globalConf.static_file_type.split('|');
}else{
    throw new Error('缺少配置参数：static_file_type');
}
function isStatic(pathName){
    for(let i = 0 ; i < static_file_type_arr.length ; i++){
        let tem = static_file_type_arr[i];
        if(pathName.indexOf(tem) === pathName.length - tem.length){
            return true;
        }
    }
    return false;
}
http.createServer((req , res) => {
    let pathName = url.parse(req.url).pathname;
    // console.log(pathName , isStatic(pathName));
    if(isStatic(pathName)){
        console.log('静态资源')
        try {
            let fsCon = fs.readFileSync(globalConf.page_path + pathName);
            res.writeHead(200);
            res.write(fsCon);
            // console.log(fsCon)
            res.end();
        } catch (error) {
            console.log('404')        
            res.writeHead(404);
            res.write("<h1>404 notfound</h1>");
            res.end();
        }
    }else{
        console.log("动态资源" , pathName , loader.get(pathName));
        if(loader.get(pathName) != null){
            loader.get(pathName)(req , res);
        }else{
            console.log('404')        
            res.writeHead(404);
            res.write("<h1>404 notfound</h1>");
            res.end();
        }
    }
}).listen(globalConf.port , () => {
    console.log('服务器已启动，监听' + globalConf.port + '端口')
});